const Koa =require("koa");
const app=new Koa();
const static=require("koa-static");
const router=require("koa-router")()
const bodyparser=require("koa-bodyparser")
const mongoose=require("mongoose");
const multer=require('koa-multer')
const {
    AddCategory ,
    GetCategory ,
    UpdateCategory ,
    CategoryName
} =require("./controller/category")
const {
    UploadPicture ,
    RemovePicture ,
    AddProduct ,
    GetProduct ,
    SearchProduct ,
    UpdateProduct ,
    RemoveProduct
} =require("./controller/product")

const {
    AddRole,
    GetRole,
    UpdateRole,
    SingleRole
} =require("./controller/role")

const {
    AddUser,
    GetUser,
    UpdateUser,
    DeleteUser
} =require("./controller/user")

const userSchema=require("./schema/userschema")

app.use(static("./public"))
app.use(bodyparser())

app.use(router.routes());   /*启动路由*/


//登陆路由
router.post("/login",async ctx=>{
    const {userName,passWord}=ctx.request.body;
    console.log(userName,passWord)
    const user=await userSchema.findOne({userName,passWord})
    console.log(user)
    if(user){
        ctx.body={
            status:0,
            data:user,
            info:"登陆成功"
        }
    }else{
        ctx.body={
            status:1,
            info:"登陆失败！用户名或密码错误"
        }
    }
})

// 分类路由
router.post("/category/add", AddCategory)
router.get("/category/get",GetCategory)
router.post("/category/updatename",UpdateCategory)
router.get("/category/name",CategoryName);


//文件上传配置
var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");  //以点分割成数组，数组的最后一项就是后缀名
        cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
//加载配置
var upload = multer({ storage: storage });
//图片路由
router.post('/image/upload',upload.single('image'),UploadPicture)
router.post("/image/remove",RemovePicture)

//商品路由
router.post("/product/add",AddProduct)
router.post("/product/get",GetProduct)
router.get("/product/search",SearchProduct)
router.post("/product/update",UpdateProduct)
router.post("/product/remove",RemoveProduct)

//角色路由
router.post("/role/add",AddRole)
router.get("/role/get",GetRole)
router.post("/role/update",UpdateRole)
router.get("/role/singlerole",SingleRole)

//用户路由
router.post("/user/add",AddUser)
router.get("/user/get",GetUser)
router.post("/user/update",UpdateUser)
router.post("/user/delete",DeleteUser)


mongoose.connect("mongodb://localhost:27018/react-data",{
    useNewUrlParser:true,
    useUnifiedTopology:true
}).then(()=>{
    console.log("react-data数据库连接成功")
    app.listen("5000",function(){
        console.log("5000端口已启动")
    })
}).catch(()=>{
    console.log("react-data数据库连接失败")
})

